<?php

namespace App\Console\Commands;

use App\Library\Logic\CouponLogic;
use App\Library\Logic\CouponUserRelatedLogic;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;

class CouponExpireCommand extends Command
{
    /**
     * 优惠券过期处理
     *
     * @var string
     */
    protected $signature = 'command:couponExpire';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * 优惠券过期
     * Execute the console command.
     */
    public function handle(): void
    {
        $expireCoupon = CouponLogic::query()->where('exp_end_at', '<=', now()->toDateTimeString())->get();
        $sendEndCoupon = CouponLogic::query()->where('send_end_at', '<=', now()->toDateTimeString())->get();

        if (!is_null($expireCoupon)) {
            $expireIdArr = [];
            foreach ($expireCoupon as $value) {
                $expireIdArr[] = $value->id;
            }

            CouponLogic::query()->whereIn('id', $expireIdArr)->update(['is_expire' => 1]);
            CouponUserRelatedLogic::query()->whereIn('coupon_id', $expireIdArr)->update(['status' => 2]);
        }

        if (!is_null($sendEndCoupon)) {
            $endIdArr = [];
            foreach ($sendEndCoupon as $value) {
                $endIdArr[] = $value->id;
            }
            CouponLogic::query()->whereIn('id', $endIdArr)->update(['status' => 3]);
        }
    }
}
